package pl.ydp.ivy.flex.ide;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.module.id.ModuleId;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.plugins.parser.ModuleDescriptorParserRegistry;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;

import pl.ydp.ivy.IIvyProvider;

public class WorkspaceIvyProjects {
	
	private Map<ModuleId, IProject> ivyToProject = new HashMap<ModuleId, IProject>();
	
	public WorkspaceIvyProjects() {
		scan( ResourcesPlugin.getWorkspace().getRoot() );
	}
	
	public WorkspaceIvyProjects( IWorkspaceRoot root ) {
		scan(root);
	}
	
	public IProject findProject( ModuleRevisionId module ) {
		return findProject( module.getModuleId() );
	}
	
	public IProject findProject( ModuleId module ) {
		return ivyToProject.get( module );
	}
	
	protected void scan( IWorkspaceRoot root ) {
		for( IProject project: root.getProjects() ) {
			IIvyProvider ivyProvider = 
				Activator.getDefault().getIvyProvider().getProjectIvyProvider(project);
			
			try {
				if ( ivyProvider.isIvyPresent() ) {
					ModuleDescriptor md = ModuleDescriptorParserRegistry.getInstance().parseDescriptor( 
							ivyProvider.getIvySettings(), 
							ivyProvider.getIvyFile().toURI().toURL(), false);
					
					ivyToProject.put( md.getModuleRevisionId().getModuleId(), project );
				}
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
